package com.af.dao.pay.impl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Map;

import org.apache.log4j.Logger;

import com.af.common.Log4jXmlConfig;
import com.af.common.PropertiesManager;
import com.af.common.SignUtil;
import com.af.dao.pay.PaySendReqRes;

public class WebSocket {

	Logger LOG = Log4jXmlConfig.getInstance().returnLogger(WebSocket.class);

	/**
	 * 获取通信端的返回信息
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public String returnWebResponse(Map params) {
		String postData = SignUtil.createSortLinkString(params);
		PaySendReqRes.insertSendRequest(params);
		return publicMethod(postData);
	}

	private String publicMethod(String postData) {
		HttpURLConnection httpURLConnection;
		StringBuilder sb = null;
		try {
			URL url = new URL(PropertiesManager.getInstance().returnValue(
					"pay_url"));
			httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setConnectTimeout(10000);
			httpURLConnection.setReadTimeout(30000);
			httpURLConnection.connect();
			BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
					httpURLConnection.getOutputStream(), "UTF-8"));
			out.write(postData);
			out.flush();
			out.close();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					(InputStream) httpURLConnection.getInputStream()));
			String line = null;
			sb = new StringBuilder();
			while ((line = in.readLine()) != null) {
				sb.append(line);
			}
			in.close();
			httpURLConnection.disconnect();
			LOG.info(postData);
		} catch (MalformedURLException e) {

			LOG.error(e.getMessage());

			LOG.error(postData);

			e.printStackTrace();
		} catch (ProtocolException e) {

			LOG.error(e.getMessage());

			LOG.error(postData);
			
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			
			LOG.error(e.getMessage());

			LOG.error(postData);
			
			e.printStackTrace();
		} catch (IOException e) {
			LOG.error(e.getMessage());

			LOG.error(postData);
			
			e.printStackTrace();
		}
		return sb.toString();
	}
}
